﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace AutoHistory.Core
{
    [Serializable]
    public class Settings
    {
        public int MaxHistoryFiles { get; set; }

        public int Language { get; set; }

        public bool UseGlobalHistoryLocation { get; set; }

        public string GlobalHistoryLocation { get; set; }

        public bool IsPaneVisible { get; set; }

        public Settings() { }

        private static Settings instance;

        public static Settings Instance
        {
            get
            {
                if (instance == null)
                    instance = Settings.Load();

                if (instance == null)
                    instance = new Settings();

                return instance;
            }
        }

        private static string GetSettingsFile()
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AutoHistory");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            return Path.Combine(path, "Settings.xml");
        }

        public void Save()
        {
            try
            {
                XmlSerializer xml = new XmlSerializer(typeof(Settings));
                using (FileStream fs = new FileStream(Settings.GetSettingsFile(), FileMode.Create))
                {
                    xml.Serialize(fs, this);
                }
            }
            catch { throw; }
        }

        private static Settings Load()
        {
            try
            {
                Settings returnData = null;
                XmlSerializer xml = new XmlSerializer(typeof(Settings));
                using (FileStream fs = new FileStream(Settings.GetSettingsFile(), FileMode.Open))
                {
                    returnData = (Settings)xml.Deserialize(fs);
                }
                return returnData;
            }
            catch (Exception) { return null; }
        }
    }
}
